package com.dubbo.framework.register;

import cn.hutool.core.convert.Convert;
import cn.hutool.setting.dialect.Props;
import com.alibaba.fastjson.JSONObject;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

import static com.dubbo.framework.consts.DubboConstant.*;

/**
 * 远程注册中心 基于zk,使用单例模式
 *
 * @author by Mr. Li 2021/4/29 10:47
 */
public class RemoteMapRegister implements Register {

    public static CuratorFramework client;

    // 读取远程注册中心的服务
    static {
        // 读取配置类
        Props props = new Props("zookeeper.properties");
        final String zkAddr = (String) props.get(ZK_ADDR);
        // 使用curator连接zookeeper
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 5);

        client = CuratorFrameworkFactory.builder()
                .connectString(zkAddr)
                .sessionTimeoutMs(Convert.toInt(props.get(ZK_SESSION_TIMEOUT_MS)))
                .connectionTimeoutMs(Convert.toInt(props.get(ZK_CONNECTION_TIMEOUT_MS)))
                .namespace(ZK_REGISTER_NAMESPACE) //命名空间。
                .retryPolicy(retryPolicy)
                .build();  // 建立连接通道。
        client.start();
    }

    /**
     * 将元信息注册到 zk上
     *
     * @param interfaceName 接口名
     * @param implClass     实现类
     */
    @Override
    public void register(String interfaceName, Class implClass) {
        // 将服务信息注册到 zk中
        try {
            // 创建临时节点
            client.create().withMode(CreateMode.EPHEMERAL).forPath("/" + interfaceName, JSONObject.toJSONBytes(implClass));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Class getMetaInfo(String interfaceName) {
        try {
            final byte[] bytes = client.getData().forPath("/" + interfaceName);
            final String fullyQualifiedName = JSONObject.parseObject(bytes, String.class);
            return Class.forName(fullyQualifiedName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
